package com.ruoyi.web.cp.service.rm;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.web.core.config.ConfigLoader;
import com.ruoyi.web.cp.domain.rm.RmResult;
import com.ruoyi.web.cp.domain.rm.RmobDoubleMerge;
import com.ruoyi.web.cp.service.WinxinService;
import com.ruoyi.web.mapper.RmResultMapper;
import com.ruoyi.web.mapper.RmobDoubleMergeMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RmResultDoubleMergeService {
    @Autowired
    private RmobDoubleMergeMapper rmobDoubleMergeMapper;
    @Autowired
    private RmResultMapper rmResultMapper;
    @Autowired
    private WinxinService winxinService;
    @Autowired
    private ConfigLoader configLoader;

    @SneakyThrows
    public void merge(Date beginDate, Date endDate) {
        beginDate = DateUtil.offsetHour(new Date(), -24);
        List<RmobDoubleMerge> rmobDoubleMergeList = getRmobDoubleMergeList(beginDate, null);
        if (CollUtil.isEmpty(rmobDoubleMergeList)) {
            return;
        }
        List<String> gameIds = rmobDoubleMergeList.stream().map(RmobDoubleMerge::getGameId)
                .distinct()
                .collect(Collectors.toList());
        List<RmResult> rmResultList = getResultsByGameIds(gameIds);
        if (CollUtil.isEmpty(rmResultList)) {
            return;
        }
        // 生成 gameId -> allScore 的字典
        Map<String, RmResult> gameIdToAllScoreMap = rmResultList.stream()
                .collect(Collectors.toMap(
                        RmResult::getGameId,
                        v -> v,
                        (existing, replacement) -> existing
                ));

        // 后续可以使用该字典进行匹配、更新等操作
        // 例如：遍历 rmobDoubleMergeList 并关联 allScore
        for (RmobDoubleMerge merge : rmobDoubleMergeList) {
            RmResult rmResult = gameIdToAllScoreMap.get(merge.getGameId());
            if (rmResult != null) {
                // 假设 RmobDoubleMerge 有 setAllScore 方法
                merge.setRmResult(rmResult);
                // 可以继续做其他业务处理
            }
        }

        String path = configLoader.getRmPath() + "双进结果.xlsx";
        File tempFile = new File(path);
        // 如果文件已存在，先删除
        if (tempFile.exists()) {
            FileUtil.del(tempFile);
        }
        // 导出到 Excel
        exportRmobDoubleMergeToExcel(rmobDoubleMergeList, tempFile);
        winxinService.uploadMediaByAppAndSendMsg("1000016", path);
    }

    public List<RmobDoubleMerge> getRmobDoubleMergeList(Date beginDate, Date endDate) {
        return rmobDoubleMergeMapper.selectByDateBetween(beginDate, endDate);
    }

    public List<RmResult> getResultsByGameIds(List<String> gameIds) {
        return rmResultMapper.selectByGameIds(gameIds);
    }

    public void exportRmobDoubleMergeToExcel(List<RmobDoubleMerge> rmobDoubleMergeList, File tempFile) {
        // 创建 ExcelWriter 对象
        ExcelWriter writer = ExcelUtil.getWriter(tempFile);

        // 手动设置表头
        String[] headers = {"日期", "联赛", "主队", "客队", "RM赔率",
                "OB双进赔率", "OB00赔率", "大小球", "大球赔率", "小球赔率",
                "独赢主赔率", "独赢平赔率", "独赢客赔率", "亚盘让球", "亚盘上盘赔率",
                "亚盘下盘赔率", "首进球时间", "半场结果", "全场结果", "红黑"};
        writer.writeHeadRow(Arrays.asList(headers));

        // 写入数据（假设 RmobDoubleMerge 有对应的 getter 方法）
        for (RmobDoubleMerge item : rmobDoubleMergeList) {
            if (item.getDetailsJson() == null) {
                continue;
            }
            Date date = item.getDate();
            JSONObject detail = item.getDetailsArray().getJSONObject(0);

            String dateStr = DateUtil.format(date, "yyyy-MM-dd HH:mm");
            String redBlack = "";
            RmResult rmResult = item.getRmResult();
            String goalTime = "", halfScore = "", allScore = "";
            if (rmResult != null) {
                redBlack = "0-0".equals(rmResult.getAllScore()) ? "黑" : "红";
                goalTime = rmResult.getGoalTime() == null ? "" : rmResult.getGoalTime();
                halfScore = rmResult.getHalfScore() == null ? "" : rmResult.getHalfScore();
                allScore = rmResult.getAllScore() == null ? "" : rmResult.getAllScore();
            }
            //[{"score": "0-0", "rm_plv": "2.22", "win_plv": "2.09", "draw_plv": "4.20", "lose_plv": "2.98",
            // "goal_desc": "2.5/3", "asian_desc": "+0/0.5", "bdan00_plv": "27.00", "double_plv": "1.40",
            // "goal_big_plv": "1.52", "asian_big_plv": "1.51", "goal_small_plv": "2.56", "asian_small_plv": "2.63"}]
            writer.writeRow(Arrays.asList(
                    dateStr,            // 日期
                    item.getLeague(),          // 联赛
                    item.getTeamA(),           // 主队
                    item.getTeamB(),           // 客队
                    detail.getString("rm_plv"),          // RM赔率
                    detail.getString("double_plv"),    // OB双进赔率
                    detail.getString("bdan00_plv"),        // OB00赔率
                    detail.getString("goal_desc"),        // 大小球
                    detail.getString("goal_big_plv"),        // 大球赔率
                    detail.getString("goal_small_plv"),        // 小球赔率
                    detail.getString("win_plv"),        // 独赢主赔率
                    detail.getString("draw_plv"),        // 独赢平赔率
                    detail.getString("lose_plv"),        // 独赢客赔率
                    detail.getString("asian_desc"),        // 亚盘让球
                    detail.getString("asian_big_plv"),        // 亚盘上盘赔率
                    detail.getString("asian_small_plv"),        // 亚盘下盘赔率
                    goalTime,           // 首进球时间
                    halfScore,          // 半场结果
                    allScore,          // 全场结果
                    redBlack            // 红黑
            ));
        }
        int[] columnWidths = {
                18 * 256, // 日期
                15 * 256, // 联赛
                20 * 256, // 主队
                20 * 256, // 客队
                10 * 256, // RM赔率
                14 * 256, // OB双进赔率
                12 * 256, // OB00赔率
                12 * 256, // 大小球
                12 * 256, // 大球赔率
                12 * 256, // 小球赔率
                12 * 256, // 独赢主赔率
                12 * 256, // 独赢平赔率
                12 * 256, // 独赢客赔率
                12 * 256, // 亚盘让球
                12 * 256, // 亚盘上盘赔率
                12 * 256, // 亚盘下盘赔率
                12 * 256, // 首进球时间
                15 * 256, // 半场结果
                8 * 256,  // 全场结果
                8 * 256,  // 红黑
        };

        for (int i = 0; i < columnWidths.length; i++) {
            writer.getSheet().setColumnWidth(i, columnWidths[i]);
        }
        // 关闭流
        writer.close();
    }

}
